<?php
class BlogsController extends AppController
{
    public $name = 'Blogs';
    public $components = array(
        'Email'
    );
    public $uses = array(
        'Blog',
        'EmailTemplate'
    );
    public function beforeFilter()
    {
        $this->Security->disabledFields = array(
            'Blog.publish',
            'Blog.draft'
        );
        if (!Configure::read('suspicious_detector.is_enabled') && !Configure::read('Project.auto_suspend_update_on_system_flag')) {
            $this->Blog->Behaviors->detach('SuspiciousWordsDetector');
        }
        parent::beforeFilter();
    }
    public function index()
    {
        $this->pageTitle = __l('Project Updates');
        //Redirect Get to namedparams
        $this->_redirectGET2Named(array(
            'q',
			'project_id'
        ));
		if(isset($this->request->params['named']['project_id'])){
			$this->request->data['Blog']['project_id'] = $this->request->params['named']['project_id'];
		}
        if (empty($this->request->params['named']['project_id']) && empty($this->request->params['named']['project']) && (empty($this->request->params['named']['tag'])) && (!isset($this->request->params['named']['q']))) {

            throw new NotFoundException(__l('Invalid request'));
        }
        $conditions = array();
        if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
            if ($this->Auth->user('id')) {
                $conditions['OR']['Blog.user_id'] = $this->Auth->user('id');
                $conditions['OR']['Blog.admin_suspend'] = '0';
            } else {
                $conditions['Blog.admin_suspend'] = '0';
            }
        }
        if(!empty($this->request->params['named']['tag']))
        {
         $blogTag = $this->Blog->BlogTag->find('first', array(
                'conditions' => array(
                    'BlogTag.slug' => $this->request->params['named']['tag']
                ) ,
                'fields' => array(
                    'BlogTag.name',
                    'BlogTag.slug'
                ) ,
                'contain' => array(
                    'Blog' => array(
                        'fields' => array(
                            'Blog.id'
                        )
                    )
                ) ,
                'recursive' => 1
            ));
          if (empty($blogTag)) {
                throw new NotFoundException(__l('Invalid request'));
            }
            $ids = array();
            if (!empty($blogTag)) {
                foreach($blogTag['Blog'] as $blog) {
                    $ids[] = $blog['id'];
                }
            }
            $conditions['Blog.id'] = $ids;
        }
        if (!empty($this->request->params['named']['project_id']) || !empty($this->request->params['named']['project'])) {
            $projectconditions = array();
            if (!empty($this->request->params['named']['project'])) {
                $projectconditions['Project.slug'] = $this->request->params['named']['project'];
            } else {
                $projectconditions['Project.id'] = $this->request->params['named']['project_id'];
            }
            $project_owner = $this->Blog->Project->find('first', array(
                'conditions' => $projectconditions,
                'fields' => array(
                    'Project.user_id',
                    'Project.name',
                    'Project.slug',
                    'Project.id',
                ) ,
                'recursive' => - 1
            ));
            $conditions['Blog.project_id'] = $project_owner['Project']['id'];
            $this->request->params['named']['project_id'] = $project_owner['Project']['id'];
            $this->set('project_id', $project_owner['Project']['id']);
            $this->pageTitle = $project_owner['Project']['name'] . ' - ' . __l('updates');
            $this->set('project_owner', $project_owner['Project']['user_id']);
            $this->set('project_slug', $project_owner['Project']['slug']);
        }
        if (!empty($this->request->params['named']['q'])) {
            $this->request->data['Blog']['q'] = $this->request->params['named']['q'];
            $this->pageTitle.= sprintf(' - Search - %s', $this->request->params['named']['q']);
        }
        $conditions['Blog.is_published'] = 1;
        if (isset($this->request->params['named']['status']) && $this->request->params['named']['status'] == 'drafted') {
            $conditions['Blog.is_published'] = 0;
            $this->pageTitle = __l('Drafted Updates');
        }
        if (!empty($this->request->params['named']['username'])) {
            $this->pageTitle.= sprintf(' - User - %s', $this->request->params['named']['username']);
            $conditions['User.username'] = $this->request->params['named']['username'];
        }
        if (!empty($this->request->params['named']['tag'])) {
            $blogTag = $this->Blog->BlogTag->find('first', array(
                'conditions' => array(
                    'BlogTag.slug' => $this->request->params['named']['tag']
                ) ,
                'fields' => array(
                    'BlogTag.name',
                    'BlogTag.slug'
                ) ,
                'contain' => array(
                    'Blog' => array(
                        'fields' => array(
                            'Blog.id'
                        )
                    )
                ) ,
                'recursive' => 1
            ));
            if (empty($blogTag)) {
                throw new NotFoundException(__l('Invalid request'));
            }
            $this->pageTitle.= sprintf(__l(' - Tag - %s') , $blogTag['BlogTag']['name']);
            $ids = array();
            foreach($blogTag['Blog'] as $blog) {
                $ids[] = $blog['id'];
            }
            $conditions['Blog.id'] = $ids;
        }
        $inactive_projects = array(ConstProjectStatus::Pending,ConstProjectStatus::ProjectCancelled);
        $conditions['Project.project_status_id NOT'] = $inactive_projects;
        $this->Blog->recursive = 2;
        $this->paginate = array(
            'fields' => array(
                'Blog.id',
                'Blog.title',
                'Blog.slug',
                'Blog.content',
                'Blog.project_id',
                'Blog.blog_comment_count',
                'Blog.created',
                'Blog.blog_view_count'
            ) ,
            'conditions' => $conditions,
            'contain' => array(
                'Project' => array(
                    'User' => array(
                        'UserAvatar' => array(
                            'fields' => array(
                                'UserAvatar.id',
                                'UserAvatar.dir',
                                'UserAvatar.filename',
                                'UserAvatar.width',
                                'UserAvatar.height'
                            )
                        ) ,
                        'fields' => array(
                            'User.username'
                        )
                    ) ,
                ) ,
                'BlogTag' => array(
                    'fields' => array(
                        'BlogTag.name',
                        'BlogTag.slug'
                    )
                )
            ) ,
            'order' => array(
                'Blog.id' => 'desc'
            ) ,
        );
		
		if ($this->RequestHandler->prefers('json')) {
			$iphone_project_updates = $this->paginate();
			$iphone_project_update = array();
			for($i=0;$i<count($iphone_project_updates);$i++)
			{
				$date = date('d',strtotime($iphone_project_updates[$i]['Blog']['created']));
				$month = date('F',strtotime($iphone_project_updates[$i]['Blog']['created']));
				$created = $month." ".$date;
				
				$image_options = array(
            			'dimension' => 'iphone_project_thumb',
            			'class' => '',
            			'alt' => 'alt',
            			'title' => 'title',
            			'type' => 'jpg'
        		);
				if(!empty($iphone_project_updates[$i]['Project']['User']['UserAvatar']))
				{
				$image_url = Router::url('/', true).$this->Blog->Project->getImageUrl('UserAvatar', $iphone_project_updates[$i]['Project']['User']['UserAvatar'], $image_options);
				}
				else
				{	
				$iphone_project_updates[$i]['Project']['User']['UserAvatar']['id'] = constant(sprintf('%s::%s', 'ConstAttachment', 'UserAvatar'));
				$image_url = Router::url('/', true).$this->Blog->Project->getImageUrl('UserAvatar', $iphone_project_updates[$i]['Project']['User']['UserAvatar'], $image_options);
				}
				
				$iphone_project_update[$i]['Update_id'] = $iphone_project_updates[$i]['Blog']['id'];
				$iphone_project_update[$i]['Update_title'] = $iphone_project_updates[$i]['Blog']['title'];
				$iphone_project_update[$i]['Update_description'] = $iphone_project_updates[$i]['Blog']['content'];
				$iphone_project_update[$i]['Update_slug'] = $iphone_project_updates[$i]['Blog']['slug'];
				$iphone_project_update[$i]['Comment_count'] = $iphone_project_updates[$i]['Blog']['blog_comment_count'];
				$iphone_project_update[$i]['Update_created'] = $created;
				$iphone_project_update[$i]['Update_username'] = $iphone_project_updates[$i]['Project']['User']['username'];
				$iphone_project_update[$i]['Update_user_image'] = $image_url;
				//$iphone_project_update[$i]['Update_tag'] = $iphone_project_updates[$i]['BlogTag']['name'];
			}
			$this->view = 'Json';
			$this->set('json',$iphone_project_update);
		
		}
        if (!empty($this->request->data['Blog']['q'])) {
            $this->paginate = array_merge($this->paginate, array(
				'search' => $this->request->data['Blog']['q']
			));
        }
        $this->set('blogs', $this->paginate());
    }
    public function view($slug = null)
    {
        $this->pageTitle = __l('Update');
        if (is_null($slug)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $blog = $this->Blog->find('first', array(
            'conditions' => array(
                'Blog.slug = ' => $slug
            ) ,
            'contain' => array(
                'Project' => array(
                    'User' => array(
                        'UserAvatar' => array(
                            'fields' => array(
                                'UserAvatar.id',
                                'UserAvatar.dir',
                                'UserAvatar.filename',
                                'UserAvatar.width',
                                'UserAvatar.height'
                            )
                        ) ,
                        'fields' => array(
                            'User.id',
                            'User.username',
                        ) ,
                    ) ,
                    'Attachment',
                ) ,
                'BlogTag' => array(
                    'fields' => array(
                        'BlogTag.name',
                        'BlogTag.slug',
                        'BlogTag.id'
                    )
                )
            ) ,
            'recursive' => 3
        ));
        if (empty($blog)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $this->Blog->BlogView->create();
        $this->request->data['BlogView']['user_id'] = $this->Auth->user('id');
        $this->request->data['BlogView']['blog_id'] = $blog['Blog']['id'];
		$this->request->data['BlogView']['ip_id'] = $this->Blog->BlogView->toSaveIp();
        $this->Blog->BlogView->save($this->request->data);
        $this->pageTitle.= ' - ' . $blog['Blog']['title'];
        $this->request->data['BlogComment']['blog_id'] = $blog['Blog']['id'];
        $this->set(compact('blog'));
    }
    public function add($project_id = null)
    {
        $this->pageTitle = __l('Add New Update');
        if (!empty($this->request->data)) {
            $this->request->data['Blog']['is_published'] = (isset($this->request->data['Blog']['draft'])) ? 0 : 1;
            $this->Blog->create();
            $this->Blog->set($this->request->data);
            if ($this->Blog->validates()) {
                if (empty($this->request->data['Blog']['user_id'])) {
                    $this->request->data['Blog']['user_id'] = $this->Auth->user('id');
                }
                if ($this->Blog->save($this->request->data)) {
                    $blog = $this->Blog->find('first', array(
                        'conditions' => array(
                            'Blog.id' => $this->Blog->id
                        ) ,
                        'contain' => array(
                            'Project' => array(
                                'User' => array(
                                    'fields' => array(
                                        'User.email',
                                        'User.username'
                                    )
                                ) ,
                                'ProjectFund' => array(
                                    'fields' => array(
                                        'ProjectFund.user_id'
                                    )
                                ) ,
                                'ProjectFollower' => array(
                                    'fields' => array(
                                        'ProjectFollower.user_id'
                                    )
                                ) ,
                                'fields' => array(
                                    'Project.id',
                                    'Project.user_id',
                                    'Project.name',
                                    'Project.slug'
                                )
                            ) ,
                        ) ,
                        'recursive' => 2
                    ));
                    // send mail to backed
                    if (!$blog['Blog']['admin_suspend']) {
                        $pledged_users = Set::extract('/Project/ProjectFund/user_id', $blog);
                        $pledged_user_lists = $this->_sendAlertOnUpdate(array_unique($pledged_users) , $blog, ConstProjectUsers::Backer);
                        // send mail to followers
                        $follow_users = Set::extract('/Project/ProjectFollower/user_id', $blog);
                        $this->_sendAlertOnUpdate(array_unique($follow_users) , $blog, ConstProjectUsers::Follower, $pledged_user_lists);
                    }
                    if ($blog['Blog']['admin_suspend']) {
                        $this->Session->setFlash(__l('Update has been suspended, due to some bad words') , 'default', null, 'error');
                    } else if ($this->request->data['Blog']['is_published']) {
                        $this->Session->setFlash(__l('Project update has been published') , 'default', null, 'success');
                    } else {
                        $this->Session->setFlash(__l('Project update has been drafted') , 'default', null, 'success');
                    }
                    $this->redirect(array(
                        'controller' => 'projects',
                        'action' => 'view',
                        $blog['Project']['slug'],
                        'admin' => false
                    ));
                }
            } else {
                $this->Session->setFlash(__l('Update could not be added. Please, try again.') , 'default', null, 'error');
            }
        }
        if (!empty($this->request->params['named']['project_id']) || !empty($this->request->data['Blog']['project_id'])) {
            $this->request->data['Blog']['project_id'] = !empty($this->request->params['named']['project_id']) ? $this->request->params['named']['project_id'] : $this->request->data['Blog']['project_id'];
            $project = $this->Blog->Project->find('first', array(
                'conditions' => array(
                    'Project.id' => $this->request->data['Blog']['project_id']
                ) ,
                'contain' => array(
                    'Attachment',
                ) ,
                'recursive' => 0
            ));
            $this->set('project', $project);
        }
        if ((!empty($project['Project']['user_id']) && $project['Project']['user_id'] != $this->Auth->user('id') && $this->Auth->user('user_type_id') == ConstUserTypes::User)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        if ($this->Auth->user('user_type_id') == ConstUserTypes::Admin) {
            $projects = $this->Blog->Project->find('list');
            $this->set(compact('projects'));
        }
    }
    public function _sendAlertOnUpdate($userIds, $blog, $projectUserType, $user_lists = array())
    {
        if (!empty($userIds)) {
            $users = $this->Blog->Project->User->find('all', array(
                'conditions' => array(
                    'User.id' => $userIds,
                ) ,
                'fields' => array(
                    'User.email',
                    'User.id',
                    'User.username',
                ) ,
                'recursive' => - 1
            ));
            // Send private messsage on project comment add
            $subject = __l('New Project Update');
            $message = $this->Auth->User('username') . ' ' . __l('has added new update on project') . ' "' . $blog['Project']['name'] . '"';
            $message_id = $this->Blog->Project->Message->sendNotifications($userIds, $subject, $message, $blog['Project']['id']);
            $email_message = $this->EmailTemplate->selectTemplate('Project Update Add Alert');
            foreach($users as $user) {
                if (!in_array($user['User']['id'], $user_lists)) {
                    $user_preference = $this->Blog->_getPermissionPerference($user['User']['id']);
                    if (($projectUserType == ConstProjectUsers::Backer && $user_preference['UserPermissionPreference']['blog_mail_send_backers'] == 1) || ($projectUserType == ConstProjectUsers::Follower && $user_preference['UserPermissionPreference']['blog_mail_send_followers'] == 1)) {
                        $emailFindReplace = array(
                            '##FROM_EMAIL##' => $this->Blog->changeFromEmail(($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from']) ,
                            '##USERNAME##' => $user['User']['username'],
                            '##SITE_NAME##' => Configure::read('site.name') ,
                            '##PROJECT_NAME##' => $blog['Project']['name'],
                            '##BLOG_TITLE##' => $blog['Blog']['title'],
                            '##BLOG_LINK##' => Router::url(array(
                                'controller' => 'blogs',
                                'action' => 'view',
                                $blog['Blog']['slug'],
                                'admin' => false
                            ) , true) ,
                            '##SITE_URL##' => Router::url('/', true) ,
                        );
                        $this->Email->from = ($email_message['from'] == '##FROM_EMAIL##') ? Configure::read('EmailTemplate.from_email') : $email_message['from'];
                        $this->Email->replyTo = ($email_message['reply_to'] == '##REPLY_TO_EMAIL##') ? Configure::read('EmailTemplate.reply_to_email') : $email_message['reply_to'];
                        $this->Email->to = $user['User']['email'];
                        $this->Email->subject = strtr($email_message['subject'], $emailFindReplace);
                        $this->Email->sendAs = !empty($email_message['is_html']) ? 'html' : 'text';
                        $this->Email->send(strtr($email_message['email_content'], $emailFindReplace));
                    }
                    $user_lists[] = $user['User']['id'];
                }
            }
        }
        return $user_lists;
    }
    public function edit($id = null)
    {
        $this->pageTitle = __l('Edit Update');
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        if (!empty($this->request->data)) {
            $this->request->data['Blog']['is_published'] = (isset($this->request->data['Blog']['draft'])) ? 0 : 1;
            $this->Blog->set($this->request->data);
            if ($this->Blog->validates()) {
                if ($this->Blog->save($this->request->data)) {
                    $this->Session->setFlash(__l('Project update has been updated') , 'default', null, 'success');
                    $blog = $this->Blog->find('first', array(
                        'fields' => array(
                            'Project.slug'
                        ) ,
                        'conditions' => array(
                            'Blog.id' => $id
                        ) ,
                        'recursive' => 0
                    ));
                    if (!empty($this->request->params['admin'])) {
                        $this->redirect(array(
                            'controller' => 'blogs',
                            'action' => 'index',
                            'admin' => 'true',
                        ));
                    } else {
                        $this->redirect(array(
                            'controller' => 'projects',
                            'action' => 'view',
                            $blog['Project']['slug'],
                            'admin' => false
                        ));
                    }
                }
            } else {
                $this->Session->setFlash(__l('Update could not be updated. Please, try again.') , 'default', null, 'error');
            }
        } else {
            $conditions = array(
                'Blog.id' => $id
            );
            $this->request->data = $this->Blog->find('first', array(
                'fields' => array(
                    'Blog.title',
                    'Blog.slug',
                    'Blog.content',
                    'Blog.project_id',
                    'Blog.is_published'
                ) ,
                'conditions' => $conditions,
                'contain' => array(
                    'BlogTag' => array(
                        'fields' => array(
                            'BlogTag.name'
                        )
                    )
                ) ,
                'recursive' => 2
            ));
            if (empty($this->request->data)) {
                throw new NotFoundException(__l('Invalid request'));
            }
            if (!empty($this->request->data['BlogTag'])) {
                $this->request->data['Blog']['tag'] = $this->Blog->formatTags($this->request->data['BlogTag']);
            }
        }
        $this->pageTitle.= ' - ' . $this->request->data['Blog']['title'];
        $project = $this->Blog->Project->find('first', array(
            'conditions' => array(
                'Project.id' => $this->request->data['Blog']['project_id']
            ) ,
            'contain' => array(
                'Attachment',
            ) ,
            'recursive' => 0
        ));
        $this->set('project', $project);
        if ($this->Auth->user('user_type_id') == ConstUserTypes::Admin) {
            $projects = $this->Blog->Project->find('list');
            $this->set(compact('projects'));
        }
    }
    public function delete($id = null)
    {
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $blog = $this->Blog->find('first', array(
            'conditions' => array(
                'Blog.id' => $id,
            ) ,
        ));
        if ($this->Blog->delete($id)) {
            $this->Session->setFlash(__l('Project update deleted') , 'default', null, 'success');
            $this->redirect(array(
                'controller' => 'projects',
                'action' => 'view',
                $blog['Project']['slug'],
                'admin' => false
            ));
        } else {
            throw new NotFoundException(__l('Invalid request'));
        }
    }
    public function admin_index($status = null)
    {
        $this->_redirectGET2Named(array(
            'q'
        ));
        $conditions = array();
        if (!empty($this->request->params['named']['project_id'])) {
            $project_name = $this->Blog->Project->find('first', array(
                'conditions' => array(
                    'Project.id' => $this->request->params['named']['project_id'],
                ) ,
                'fields' => array(
                    'Project.name',
                ) ,
                'recursive' => - 1,
            ));
            $this->pageTitle = sprintf(__l('Project Updates - %s') , $project_name['Project']['name']);
            $conditions['Blog.project_id'] = $this->request->params['named']['project_id'];
        } else {
            $this->pageTitle = __l('Project Updates');
        }
        if (!empty($this->request->params['named']['category'])) {
            $blogCategory = $this->{$this->modelClass}->BlogCategory->find('first', array(
                'conditions' => array(
                    'BlogCategory.id' => $this->request->params['named']['category']
                ) ,
                'fields' => array(
                    'BlogCategory.id',
                    'BlogCategory.title',
                ) ,
                'recursive' => - 1
            ));
            if (empty($blogCategory)) {
                throw new NotFoundException(__l('Invalid request'));
            }
            $conditions['BlogCategory.id'] = $blogCategory['BlogCategory']['id'];
            $this->pageTitle.= sprintf(__l(' - %s') , $blogCategory['BlogCategory']['title']);
        }
        if (isset($this->request->params['named']['stat']) && $this->request->params['named']['stat'] == 'day') {
            $conditions['TO_DAYS(NOW()) - TO_DAYS(Blog.created) <= '] = 0;
            $this->pageTitle.= __l(' - Created today');
        }
        if (isset($this->request->params['named']['stat']) && $this->request->params['named']['stat'] == 'week') {
            $conditions['TO_DAYS(NOW()) - TO_DAYS(Blog.created) <= '] = 7;
            $this->pageTitle.= __l(' - Created in this week');
        }
        if (isset($this->request->params['named']['stat']) && $this->request->params['named']['stat'] == 'month') {
            $conditions['TO_DAYS(NOW()) - TO_DAYS(Blog.created) <= '] = 30;
            $this->pageTitle.= __l(' - Created in this month');
        }
        if (isset($this->request->params['named']['q'])) {
            $this->request->data['Blog']['q'] = $this->request->params['named']['q'];
            $conditions['AND']['OR']['Blog.title LIKE'] = '%' . $this->request->params['named']['q'] . '%';
            $conditions['AND']['OR']['Project.name LIKE'] = '%' . $this->request->params['named']['q'] . '%';
            $conditions['AND']['OR']['User.username LIKE'] = '%' . $this->request->params['named']['q'] . '%';
            $this->pageTitle.= sprintf(__l(' - Search - %s') , $this->request->params['named']['q']);
        }
        if (isset($this->request->params['named']['filter_id'])) {
            $this->request->data['Blog']['filter_id'] = $this->request->params['named']['filter_id'];
        }
        if (!empty($this->request->data['Blog']['filter_id'])) {
            if ($this->request->data['Blog']['filter_id'] == ConstMoreAction::Active) {
                $conditions['Blog.is_published'] = 1;
                $this->pageTitle.= __l(' - Published');
            } else if ($this->request->data['Blog']['filter_id'] == ConstMoreAction::Inactive) {
                $conditions['Blog.is_published'] = 0;
                $this->pageTitle.= __l(' - Draft');
            } else if ($this->request->data['Blog']['filter_id'] == ConstMoreAction::Suspend) {
                $conditions['Blog.admin_suspend'] = 1;
                $this->pageTitle.= __l(' - Suspended ');
            } elseif ($this->request->data['Blog']['filter_id'] == ConstMoreAction::Active) {
                $conditions['Blog.is_active'] = 1;
                $conditions['Blog.admin_suspend'] = 0;
                $this->pageTitle.= __l(' - Active ');
            } elseif ($this->request->data['Blog']['filter_id'] == ConstMoreAction::Inactive) {
                $conditions['Blog.is_active'] = 0;
                $this->pageTitle.= __l(' - Inactive ');
            } elseif ($this->request->data['Blog']['filter_id'] == ConstMoreAction::Flagged) {
                $conditions['Blog.is_system_flagged'] = 1;
                $this->pageTitle.= __l(' - Flagged ');
            }
            $this->request->params['named']['filter_id'] = $this->request->data['Blog']['filter_id'];
        }
        $this->Blog->recursive = 2;
        $this->paginate = array(
            'conditions' => $conditions,
            'contain' => array(
                'User' => array(
                    'fields' => array(
                        'User.username'
                    )
                ) ,
                'Project' => array(
                    'fields' => array(
                        'Project.id',
                        'Project.name',
                        'Project.slug',
                    ) ,
                    'ProjectStatus',
                ) ,
                'BlogTag' => array(
                    'fields' => array(
                        'BlogTag.name',
                        'BlogTag.slug'
                    )
                )
            ) ,
            'order' => array(
                'Blog.id' => 'desc'
            ) ,
        );
        if (!empty($this->request->data['Blog']['q'])) {
            $this->paginate = array_merge($this->paginate, array(
				'search' => $this->request->data['Blog']['q']
			));
        }
        $this->set('blogs', $this->paginate());
        // To get published and drafted blogs count
        $published_blogs = $this->Blog->find('count', array(
            'conditions' => array(
                'Blog.is_published' => 1
            )
        ));
        $drafted_blogs = $this->Blog->find('count', array(
            'conditions' => array(
                'Blog.is_published' => 0
            )
        ));
        $this->set('suspended', $this->Blog->find('count', array(
            'conditions' => array(
                'Blog.admin_suspend = ' => 1,
            )
        )));
        $this->set('system_flagged', $this->Blog->find('count', array(
            'conditions' => array(
                'Blog.is_system_flagged = ' => 1,
            )
        )));
        $this->set('published_blogs', $published_blogs);
        $this->set('drafted_blogs', $drafted_blogs);
        $filters = $this->Blog->isFilterOptions;
        $moreActions = $this->Blog->moreActions;
        $this->set(compact('filters', 'moreActions'));
    }
    public function admin_view($slug = null)
    {
        $this->setAction('view', $slug);
    }
    public function admin_add()
    {
        $this->setAction('add');
    }
    public function admin_edit($id = null)
    {
        $this->setAction('edit', $id);
    }
    public function admin_delete($id = null)
    {
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        if ($this->Blog->delete($id)) {
            $this->Session->setFlash(__l('Project update deleted') , 'default', null, 'success');
            $this->redirect(array(
                'action' => 'index'
            ));
        } else {
            throw new NotFoundException(__l('Invalid request'));
        }
    }
    public function admin_update()
    {
        if (!empty($this->request->data['Blog'])) {
            $r = $this->request->data[$this->modelClass]['r'];
            $actionid = $this->request->data[$this->modelClass]['more_action_id'];
            unset($this->request->data[$this->modelClass]['r']);
            unset($this->request->data[$this->modelClass]['more_action_id']);
            $blogIds = array();
            $this->Blog->Behaviors->detach('Logable');
            foreach($this->request->data['Blog'] as $blog_category_id => $is_checked) {
                if ($is_checked['id']) {
                    $blogIds[] = $blog_category_id;
                }
            }
            if ($actionid && !empty($blogIds)) {
                if ($actionid == ConstMoreAction::Inactive) {
                    foreach($blogIds as $val) {
                        $blog['Blog']['is_published'] = 0;
                        $blog['Blog']['id'] = $val;
                        $this->Blog->save($blog, false);
                    }
                    $this->Session->setFlash(__l('Checked project update has been inactivated') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Active) {
                    foreach($blogIds as $val) {
                        $blog['Blog']['is_published'] = 1;
                        $blog['Blog']['id'] = $val;
                        $this->Blog->save($blog, false);
                    }
                    $this->Session->setFlash(__l('Checked project update has been activated') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Delete) {
                    foreach($blogIds as $val) {
                        $this->Blog->delete($val, false);
                    }
                    $this->Session->setFlash(__l('Checked project update has been deleted') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Suspend) {
                    foreach($blogIds as $val) {
                        $blog['Blog']['admin_suspend'] = 1;
                        $blog['Blog']['id'] = $val;
                        $this->Blog->save($blog, false);
                    }
                    $this->Session->setFlash(__l('Checked project update has been Suspended') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Unsuspend) {
                    foreach($blogIds as $val) {
                        $blog['Blog']['admin_suspend'] = 0;
                        $blog['Blog']['id'] = $val;
                        $this->Blog->save($blog, false);
                    }
                    $this->Session->setFlash(__l('Checked project update has been Unsuspended') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Flagged) {
                    $this->Blog->updateAll(array(
                        'Blog.is_system_flagged' => 1
                    ) , array(
                        'Blog.id' => $blogIds
                    ));
                    $this->Session->setFlash(__l('Checked project update has been Flagged') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Unflagged) {
                    $this->Blog->updateAll(array(
                        'Blog.is_system_flagged' => 0
                    ) , array(
                        'Blog.id' => $blogIds
                    ));
                    $this->Session->setFlash(__l('Checked project update has been Unflagged') , 'default', null, 'success');
                }
            }
        }
        $this->redirect(Router::url('/', true) . $r);
    }
    public function admin_update_stats($id = null)
    {
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $this->Blog->Behaviors->detach('Logable');
        if (!empty($this->request->params['named']['flag']) && ($this->request->params['named']['flag'] == 'active')) {
            $this->Blog->updateAll(array(
                'Blog.is_system_flagged' => 1
            ) , array(
                'Blog.id' => $id
            ));
            $this->Session->setFlash(__l('Project update has been flagged') , 'default', null, 'success');
        } elseif (!empty($this->request->params['named']['flag']) && ($this->request->params['named']['flag'] == 'deactivate')) {
            $this->Blog->updateAll(array(
                'Blog.is_system_flagged' => 0
            ) , array(
                'Blog.id' => $id
            ));
            $this->Session->setFlash(__l('Project update has been Unflagged') , 'default', null, 'success');
        } elseif (!empty($this->request->params['named']['flag']) && ($this->request->params['named']['flag'] == 'suspend')) {
            $blog['Blog']['id'] = $id;
            $blog['Blog']['admin_suspend'] = 1;
            $this->Blog->save($blog, false);
            $this->Session->setFlash(__l('Project update has been suspend') , 'default', null, 'success');
        } elseif (!empty($this->request->params['named']['flag']) && ($this->request->params['named']['flag'] == 'unsuspend')) {
            $blog['Blog']['admin_suspend'] = 0;
            $blog['Blog']['id'] = $id;
            $this->Blog->save($blog, false);
            $this->Session->setFlash(__l('Project update has been unsuspend') , 'default', null, 'success');
        }
        $this->redirect(array(
            'action' => 'index',
        ));
    }
}
?>